package com.smarth.zhizulian.http.observer.inter;

import android.app.ProgressDialog;
import android.content.Context;

import com.smarth.zhizulian.R;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.exception.ApiException;
import com.smarth.zhizulian.http.exception.NoNetException;
import com.smarth.zhizulian.http.exception.UnLoginException;
import com.smarth.zhizulian.utils.KumaToast;

import org.simple.eventbus.EventBus;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by 18865 on 2017/12/25.
 * 只对异常处理的抽象类，对apiexception进行了单独处理,未知异常输出原因
 */

public abstract class BaseObserver<T> implements Observer<T> {
    protected Context mOContext;

    public BaseObserver(Context context) {
        this.mOContext = context;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onError(@NonNull Throwable e) {
        e.printStackTrace();
        if (e instanceof ApiException) {
            ApiException a = (ApiException) e;
            BaseEntity be = a.getBe();
            onErrorApi(be);
        } else if (e instanceof NoNetException) {
            onErrorNoNet((NoNetException) e);
        } else if (e instanceof UnLoginException) {
            onErrorUnLogin(e);
        } else {
            onErrorUnknown(e);
        }
    }

    public void onErrorNoNet(NoNetException e) {
//        KumaToast.show(mContext, mContext.getString(R.string.network_unconnect));
        KumaToast.show(mOContext, "请检查网络后重试");
    }

    public void onErrorApi(BaseEntity be) {
        KumaToast.show(mOContext, be.getMessage());
        if (BaseConfig.NetWork.CODE_TOKENEXPIRED.equals(be.getCode())) {
            EventBus.getDefault().post(new EventBean(be.getMessage()), BaseConfig.EventTag.RELOGIN);
        }
    }

    public void onErrorUnknown(Throwable e) {
        KumaToast.showError(mOContext, e.getMessage());
    }

    @Override
    public void onComplete() {

    }

    public void onErrorUnLogin(Throwable e) {

    }

}
